package com.example.controller;


import cn.hutool.core.date.DateUtil;
import com.example.entity.UploadFile;
import com.example.mapper.UploadFileMapper;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;

/**
 * @author 叶凯乐
 */
@Controller
@CrossOrigin(allowCredentials = "true",allowedHeaders = "*")
public class UploadFileController {

    private static final String PATH_IMG = "C:\\img\\";

    @Resource
    private UploadFileMapper uploadFileMapper;

    @PostMapping("/upload")
    @ResponseBody
    public boolean upload(@RequestParam("file") MultipartFile file,
                         @RequestParam("userId") String userId) {

        if (file.isEmpty()) {
            return false;
        }
        //要上传的文件信息
        UploadFile uploadFile = new UploadFile();
        uploadFile.setFileName(file.getOriginalFilename());
        uploadFile.setUploadTime(DateUtil.now());
        uploadFile.setUserId(userId);

        File dest = new File(PATH_IMG + file.getOriginalFilename());
        try {
            //上传文件到本地
            file.transferTo(dest);
            //插入upload_File表
            uploadFileMapper.insAllUploadFileMessage(uploadFile);
            return true;
        } catch (IOException e) {
            return false;
        }
    }
}
